package com.example.wyh.intelcheckbash;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.SeismicActivity;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.task.CheckDefectActivity;
import com.example.wyh.intelcheckbash.task.CheckInfoActivity;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by WYH on 17/10/27.
 */

public class StatisticalCheckActivity extends AppCompatActivity {
    private JSONArray taskList = new JSONArray();
    private Integer currentTaskIndex = 0;
    private Spinner taskSpinner;
    private ArrayList<String> taskNames;
    private String taskXTM;
    private JSONObject taskDetail;
    private  Thread subThread;

    private String beCheckAreaCount;
    private String beCheckPointCount;
    private String beCompleteAreaCount = "--";
    private String beCompleteCheckPointCount = "--";
    private String beCompleteDefectCount = "--";
    private String beCompleteFilterCount = "--";
    private String beCompleteLostCount = "--";

    private String beShouldCheckEquipment = "--";
    private String beRegionCheckedEquipment = "--";
    private String beNoCheckEquipment = "--";

    private JSONArray currentTaskCheckedInfo;
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(StatisticalCheckActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }

        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("巡检统计");

        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.check_static);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                taskList =  null;
                currentTaskCheckedInfo = null;
                taskDetail = null;
                StatisticalCheckActivity.this.finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            taskList =  null;
            currentTaskCheckedInfo = null;
            taskDetail = null;
            this.finish();
        }
        return  true;
//        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.statistical_check);
        SysExitUtil.activityList.add(StatisticalCheckActivity.this);
        initActionBar();
        initView();
        initAction();

    }

    public void initView() {
        taskList = getTask("后夜班",taskList);
        taskList = getTask("白班",taskList);
        taskList = getTask("前夜班",taskList);
        taskList = getTask("燃料夜班",taskList);
        taskList = getTask("燃料白班",taskList);
        taskNames = getTaskNames(taskList);

        initTaskChangeButton();
        taskSpinner = initTackSpinner("选择任务", R.id.select_task, taskNames);
//        updateTask(0);
    }
    public  void  initElement(){
        TextView be_check_region_number = (TextView) findViewById(R.id.be_check_region_number);
        be_check_region_number.setText(beCheckAreaCount);
        TextView actual_region_number = (TextView) findViewById(R.id.actual_region_number);
        actual_region_number.setText(beCompleteAreaCount);
        TextView be_check_number = (TextView) findViewById(R.id.be_check_number);
        be_check_number.setText(beCheckPointCount);
        TextView actual_point_number = (TextView) findViewById(R.id.actual_point_number);
        actual_point_number.setText(beCompleteCheckPointCount);
        TextView not_check_number = (TextView) findViewById(R.id.not_check_number);
        not_check_number.setText(beCompleteLostCount);
//        TextView filter_check_number = (TextView) findViewById(R.id.filter_check_number);
//        filter_check_number.setText(beCompleteFilterCount);
        TextView error_print_number = (TextView) findViewById(R.id.error_print_number);
        error_print_number.setText(beCompleteDefectCount);

        TextView actual_region_should_check_equipment = (TextView)findViewById(R.id.actual_region_should_check_equipment);
        actual_region_should_check_equipment.setText(beShouldCheckEquipment);

        TextView actual_region_checked_equipment = (TextView)findViewById(R.id.actual_region_checked_equipment);
        actual_region_checked_equipment.setText(beRegionCheckedEquipment);

        TextView actual_region_no_check_equipment = (TextView)findViewById(R.id.actual_region_no_check_equipment);
        actual_region_no_check_equipment.setText(beNoCheckEquipment);

    }

    public void initAction() {
        Button contiueCheckButton = (Button) findViewById(R.id.continue_check_btn);
        contiueCheckButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(StatisticalCheckActivity.this, TaskCheckActivity.class));
            }
        });
        Button showErrorPointButton = (Button) findViewById(R.id.show_error_point_btn);
        showErrorPointButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(StatisticalCheckActivity.this,CheckDefectActivity.class));
            }
        });
//        Button showFilterPointButton = (Button) findViewById(R.id.show_filter_point_btn);
//        showFilterPointButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

        Button update_check_origin = (Button)findViewById(R.id.update_check_origin);
        update_check_origin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String yhxtm = LocalStorage.getUserXtm(StatisticalCheckActivity.this);
                HttpUtil.requestNetForUpdateCheckOrigin(StatisticalCheckActivity.this,taskXTM,yhxtm);
            }
        });
    }
    public void updatetaskarea(final JSONObject areaInfo)
    {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    String qyms = areaInfo.getString("qyms");
                    String xjr = areaInfo.getString("xjr");
                    TextView update_origin = (TextView)findViewById(R.id.update_origin);
                    update_origin.setText(qyms);
                    TextView update_check_people = (TextView)findViewById(R.id.update_check_people);
                    update_check_people.setText(xjr);
                    HttpUtil.showToast(StatisticalCheckActivity.this,"更新完毕",750);
                }catch (JSONException e)
                {

                }
            }
        });

    }

    public void showStatisticalResult(int position) {
        currentTaskCheckedInfo = getCompleteXMInfo(taskXTM);
        taskDetail = getTaskDetail(position);
        JSONArray scanInfos = getAllScanInfo();

        getBeCheckInfo(scanInfos);
        getBeCompleteInfo(scanInfos);
        beCompleteLostCount = Integer.toString(Integer.parseInt(beCheckPointCount) - Integer.parseInt(beCompleteCheckPointCount));
        beNoCheckEquipment = Integer.toString(getBeNoCheckEquipment(scanInfos));
        initElement();
    }
    public int getRegionCheckedEquipmentXMNumber(JSONArray scanInfos,JSONObject localStatus)
    {
        int beRegionCheckedEquipmentNumber = 0;
        //// TODO: 17/12/19 获取实到区域当前状态下的实际巡检项目点
        for (int i = 0; i < currentTaskCheckedInfo.length(); i++) {
            JSONArray xmInfos = new JSONArray();
            try {
                if (isExist(scanInfos,currentTaskCheckedInfo.getJSONObject(i).getString("qyms")))
                {
                    String qysbxtm = currentTaskCheckedInfo.getJSONObject(i).getString("qysbxtm");
                    String equipmentStatus = localStatus.getString(qysbxtm);
                    try {
                        equipmentStatus = localStatus.getString(qysbxtm);
                    }
                    catch (JSONException e)
                    {
                        equipmentStatus = null;
                    }
                    if (equipmentStatus != null && currentTaskCheckedInfo.getJSONObject(i).getString("sbzt").equals(equipmentStatus))
                    {
                        xmInfos = currentTaskCheckedInfo.getJSONObject(i).getJSONArray("xmdata");
                        if (xmInfos.length() > 0)
                        {
                            for (int n = 0; n < xmInfos.length(); n ++)
                            {
                                try {
                                    JSONObject xmInfo = xmInfos.getJSONObject(n);
                                    if (xmInfo.getString("cdjg").length() != 0)
                                    {
                                        beRegionCheckedEquipmentNumber ++;
                                    }
                                }catch (JSONException e)
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    Log.e("currentTaskCheckedInfo",currentTaskCheckedInfo.toString());
                }
            }catch (JSONException e)
            {
                Log.e("===========JSONException",e.getMessage());
            }
        }
        return beRegionCheckedEquipmentNumber;
    }
    public int getActualAreaShouldCheckXMNumber(JSONArray scanInfos,JSONObject localStatus)
    {
        // TODO: 17/12/19  获取实到区域应检项目点
        int actualAreaShouldCheckXMNumber = 0;
        try {
            JSONArray areas = taskDetail.getJSONArray("data");
            for (int i = 0; i < areas.length(); i++) {

                if (isExist(scanInfos,areas.getJSONObject(i).getString("description")))
                {
                    JSONArray equipments = areas.getJSONObject(i).getJSONArray("data");
                    for (int m = 0; m < equipments.length(); m ++)
                    {
                        String equipmentStatus;
                        try {
                            equipmentStatus = localStatus.getString(equipments.getJSONObject(m).getString("xtm"));
                        }
                        catch (JSONException e)
                        {
                            equipmentStatus = equipments.getJSONObject(m).getString("sbzt");
                        }
                        equipmentStatus = equipmentStatus.equals("")?"运行":equipmentStatus;
                        JSONArray xmInfos = equipments.getJSONObject(m).getJSONArray("data");
                        for (int n = 0; n < xmInfos.length(); n ++)
                        {
                            if (xmInfos.getJSONObject(n).getString("qtd").contains(equipmentStatus))
                            {
                                actualAreaShouldCheckXMNumber ++;
                            }
                        }
                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return actualAreaShouldCheckXMNumber;
    }
    public int getBeNoCheckEquipment(JSONArray scanInfos)
    {
        JSONObject localStatus = LocalStorage.getObject(StatisticalCheckActivity.this, "localStatus" + HttpUtil.getCurrentDateString());
        int actualAreaShouldCheckXMNumber = getActualAreaShouldCheckXMNumber(scanInfos,localStatus);
        int beRegionCheckedEquipmentNumber = getRegionCheckedEquipmentXMNumber(scanInfos,localStatus);
        return actualAreaShouldCheckXMNumber - beRegionCheckedEquipmentNumber;
    }

    public void updateTask(int position) {
        taskSpinner.setSelection(position);

        taskXTM = getTaskXTM(position);

        showStatisticalResult(position);
    }

    public void initTaskChangeButton() {
        Button mPreTaskButton = (Button) findViewById(R.id.statistcialPreBtnTask);
        mPreTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = taskSpinner.getSelectedItemPosition();
                if (position > 0) {
                    taskSpinner.setSelection(position - 1);
                    updateTask(position - 1);
                } else {
                    Toast.makeText(StatisticalCheckActivity.this, "已经是第一个任务了", Toast.LENGTH_SHORT).show();
                }

            }
        });

        Button mNextTaskButton = (Button) findViewById(R.id.statistcialNextBtnTask);
        mNextTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = taskSpinner.getSelectedItemPosition();
                if (position < taskNames.size() - 1) {
                    taskSpinner.setSelection(position + 1);
                    updateTask(position + 1);
                } else {
                    Toast.makeText(StatisticalCheckActivity.this, "已经是最后一个任务了", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public Spinner initTackSpinner(String title, int id, ArrayList spinnerData) {
        final Spinner spinner = (Spinner) findViewById(id);
        spinner.setPrompt(title);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerData);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setSelection(position);
                updateTask(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }


    public ArrayList<String> getTaskNames(JSONArray temp) {
        ArrayList<String> names = new ArrayList<String>();
        try {
            for (int j = 0; j < temp.length(); j++) {
                names.add(temp.getJSONObject(j).getString("description"));
            }
            return names;

        } catch (Exception e) {

        }

        return names;
    }





    public JSONArray getTask( String bc, JSONArray taskList){
        TaskDbHelper taskDbHelper = new TaskDbHelper(StatisticalCheckActivity.this);
        SQLiteDatabase db =  taskDbHelper.getReadableDatabase();
//        String query =  "time = '"+ HttpUtil.getCurrentDateString()+
//                "' and user_id = '" + LocalStorage.getUserXtm(StatisticalCheckActivity.this)
//                + "'"  + " and bc = '" + bc + "'" ;
        String query =  "start_date <= '" + HttpUtil.getCurrentDateString() +
                "' and end_date >= '"  + HttpUtil.getCurrentDateString() +
                "' and user_id = '" + LocalStorage.getUserXtm(StatisticalCheckActivity.this)
                + "'"  + " and bc = '" + bc + "'" ;

        String[] columns = {"data","task_id"};
        Cursor cursor = null;
        try {
            cursor = db.query("task", columns, query, null, null, null, null);
            while (cursor.moveToNext()){

                JSONObject task = new  JSONObject();
                if(cursor.getColumnIndex("data")>-1){
                    String data =  cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        task =  new JSONObject(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                taskList.put(task);
            }
        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return  taskList;
    }




    public String getTaskXTM(int i) {
        String xtm = "";
        try {
            xtm = taskList.getJSONObject(i).getString("xtm");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return xtm;
    }

    public JSONObject getTaskDetail(int i) {
        JSONObject taskDetail = new JSONObject();
        try {
            taskDetail = taskList.getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return taskDetail;
    }

    public JSONArray getTaskAllCheckedXM(String taskXTM) {
        String key = "allCompleteCheckedTask_"+ LocalStorage.getUserXtm(StatisticalCheckActivity.this);
        JSONObject allCompleteCheckedTask = LocalStorage.getObject(StatisticalCheckActivity.this, key);
        String todayDate = HttpUtil.getCurrentDateString();
        JSONArray todayTasks = new JSONArray();
        JSONArray todayTask = new JSONArray();

        try {
            todayTasks = allCompleteCheckedTask.getJSONArray(todayDate);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < todayTasks.length(); i++) {
            try {
                String xtm = todayTasks.getJSONObject(i).getString("rwxtm");
                if (xtm.equals(taskXTM)) {
                    todayTask.put(todayTasks.getJSONObject(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return todayTask;
    }

    public void getBeCheckInfo(JSONArray scanInfos) {
        beCheckAreaCount = "--";
        beCheckPointCount = "--";
        try {
            JSONArray areas = taskDetail.getJSONArray("data");
            beCheckAreaCount = Integer.toString(areas.length());
            int count = 0;
            int actualAreaShouldCheckNumber = 0;
            for (int i = 0; i < areas.length(); i++) {
                JSONArray equipments = new JSONArray();
                try {
                    equipments = areas.getJSONObject(i).getJSONArray("data");
                } catch (JSONException e) {
                }
                for (int j = 0; j < equipments.length(); j++) {
                    try {
                        count = count+ equipments.getJSONObject(j).getJSONArray("data").length();
                    } catch (JSONException e) {

                    }
                }

                // TODO: 17/12/15  获取实到区域应检点
                if (isExist(scanInfos,areas.getJSONObject(i).getString("description")))
                {
                    actualAreaShouldCheckNumber += equipments.length();

//                    for (int m = 0; m < equipments.length(); m ++)
//                    {
//                        try {
//                            actualAreaShouldCheckNumber = actualAreaShouldCheckNumber+ equipments.getJSONObject(m).getJSONArray("data").length();
//                        } catch (JSONException e) {
//
//                        }
//                    }
                }

            }
            beCheckPointCount = Integer.toString(count);
            beShouldCheckEquipment = Integer.toString(actualAreaShouldCheckNumber);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getBeRegionCheckedEquipment(JSONArray scanInfos)
    {
        JSONArray allCheckedEquipmentXTM = new JSONArray();
        for (int i = 0; i < currentTaskCheckedInfo.length(); i++) {
            try {
                if (isExist(scanInfos,currentTaskCheckedInfo.getJSONObject(i).getString("qyms")))
                {
                    boolean isExistInChecks = false;
                    String qysbxtm = currentTaskCheckedInfo.getJSONObject(i).getString("qysbxtm");
                    //// TODO: 17/12/26 假如出现同一设备不同状态下存储的数据时，需要过滤 
                    for (int m = 0; m < allCheckedEquipmentXTM.length(); m ++)
                    {
                        if (allCheckedEquipmentXTM.getString(m).equals(qysbxtm))
                        {
                            isExistInChecks = true;
                            break;
                        }
                    }
                    if (isExistInChecks == false)
                    {
                        allCheckedEquipmentXTM.put(qysbxtm);
                    }
                }
            }catch (JSONException e)
            {
                Log.e("===========JSONException",e.getMessage());
            }
        }
        beRegionCheckedEquipment = Integer.toString(allCheckedEquipmentXTM.length());
    }
    public void getBeCompleteInfo(JSONArray scanInfos) {
//        JSONArray recodeTasks = new JSONArray();
        int checkPointCount = 0;
        int defectCount = 0;

        //获取实检区域实检点
        getBeRegionCheckedEquipment(scanInfos);

//        for (int i = 0; i < currentTaskCheckedInfo.length(); i++) {
//            try {
//                String a = currentTaskCheckedInfo.getJSONObject(i).getString("xdjqyxtm");
//                if (!isExist(recodeTasks, currentTaskCheckedInfo.getJSONObject(i).getString("xdjqyxtm"))) {
//                    recodeTasks.put(currentTaskCheckedInfo.getJSONObject(i).getString("xdjqyxtm"));
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }

        for (int i = 0; i < currentTaskCheckedInfo.length(); i++) {
            JSONArray xmInfos = new JSONArray();
            try {
                xmInfos = currentTaskCheckedInfo.getJSONObject(i).getJSONArray("xmdata");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int j = 0; j < xmInfos.length(); j++) {
                try {
                    JSONObject xmInfo = xmInfos.getJSONObject(j);
                    if (xmInfo.getString("cdjg").length() != 0)
                    {
                        checkPointCount ++;
                    }
                    if (xmInfo.getString("sfycd").equals("1")) {
                        defectCount += 1;
                    }
                } catch (JSONException e) {
                    continue;
                }
            }
        }

//        beCompleteAreaCount = Integer.toString(recodeTasks.length());
        beCompleteAreaCount = Integer.toString(scanInfos.length());
        beCompleteCheckPointCount = Integer.toString(checkPointCount);
        beCompleteDefectCount = Integer.toString(defectCount);

    }

    public JSONArray getAllScanInfo()
    {
        JSONObject mAllScanInfos = LocalStorage.getObject(StatisticalCheckActivity.this, "allScanInfo");
        JSONArray scanInfos = new JSONArray();
        try {
            String taskxtm = taskList.getJSONObject(taskSpinner.getSelectedItemPosition()).getString("xtm");
            scanInfos = mAllScanInfos.getJSONArray(taskxtm);
        }catch (JSONException e)
        {

        }
        return scanInfos;
    }
    public boolean isExist(JSONArray array, String xtm) {
        boolean isExist = false;
        for (int i = 0; i < array.length(); i++) {
            try {
                if (array.getJSONObject(i).getString("scanResult").equals(xtm)) {
                    isExist = true;
                    break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return isExist;
    }

    public JSONArray getCompleteXMInfo(String taskId) {
        JSONArray completeXmInfo = new JSONArray();
        TaskDbHelper taskDbHelper = new TaskDbHelper(StatisticalCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "time = '" + HttpUtil.getCurrentDateString() +
//                "' and user_id = '" + LocalStorage.getUserXtm(StatisticalCheckActivity.this)
//                + "'" + " and task_id = '" + taskId + "'" ;
        String query = "user_id = '" + LocalStorage.getUserXtm(StatisticalCheckActivity.this)
                + "'" + " and task_id = '" + taskId + "'" ;

        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);

            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        completeXmInfo.put(new JSONObject(data));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

}
